package com.aboo.frame;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.annotation.Resource;

@Configuration
@Aspect
public class DbUsersTransactionAdviceConfig {

	private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.aboo..service.*.*(..))";

	@Resource(name = "usersTransactionManager")
	private PlatformTransactionManager usersTransactionManager;

	/**
	 * 
	 * 方法名：  usersTxAdvice 
	 * 描述：  事物规则配置
	 * @author  娄安   
	 * 创建时间：2019年9月27日 下午1:26:57
	 * @return
	 *
	 */
	@Bean(name = "usersTxAdvice")
	public TransactionInterceptor usersTxAdvice() {
		DefaultTransactionAttribute txAttrRequired = new DefaultTransactionAttribute();
		txAttrRequired.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

		DefaultTransactionAttribute txAttrRequiredReadOnly = new DefaultTransactionAttribute();
		txAttrRequiredReadOnly.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

		NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
		source.addTransactionalMethod("save*", txAttrRequired);
		source.addTransactionalMethod("get*", txAttrRequiredReadOnly);
		return new TransactionInterceptor(usersTransactionManager, source);
	}

	/**
	 * 
	 * 方法名：  usersTxAdviceAdvisor 
	 * 描述：  事物切面
	 * @author  娄安   
	 * 创建时间：2019年9月27日 下午1:27:10
	 * @return
	 *
	 */
	@Bean(name = "usersTxAdviceAdvisor")
	public Advisor usersTxAdviceAdvisor() {
		AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
		pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
		return new DefaultPointcutAdvisor(pointcut, usersTxAdvice());
	}

}
